import axios from 'axios'
import {
  interceptorRqSuccess,
  handleErrorResponse_limit,
  handleSuccessResponse_limit
} from './cancelRq'
let request = axios.create()

// 添加请求拦截器
request.interceptors.request.use(
  async (config) => {
    await interceptorRqSuccess(config)
    config.headers.icode = 'helloqianduanxunlianying'
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    // 将拿到的结果发布给其他相同的接口
    const { code, success, data } = response.data
    if (code === 200 && success) {
      handleSuccessResponse_limit(response)
      return data
    } else {
      return handleErrorResponse_limit(response)
    }
  },
  function (error) {
    if (error?.response?.status === 401) {
      return Promise.reject('登录超时')
    }
    return handleErrorResponse_limit(error)
  }
)

export default request
